import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;

import kisti.lod.sindice.query.LiveQuery;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.sindice.SindiceException;


public class ParseErrorTest {
	
	public static void main (String[] args) throws SindiceException, SocketTimeoutException {
//		String subjectUri = "http://www.ecademy.com/module.php?mod=network&op=foafrdf&uid=93780";
//		String subjectUri = "http://www.ecademy.com/module.php?mod=network&op=foafrdf&uid=191327";
//		String subjectUri = "http://www.bibsonomy.org/bibtex/285c5aa705f715e7ae525a7fda3c93152/brazovayeye";
		String subjectUri = " http://oai.rkbexplorer.com/models/DSTO-Repository-2008.rdf";
		
//		MySindice sindice = new MySindice();
		LiveQuery liveQuery = new LiveQuery();
		
		Model model = ModelFactory.createDefaultModel();
//		Model bigModel = ModelFactory.createDefaultModel();
		
//		CacheQuery cacheQuery = new CacheQuery(subjectUri);
//		CacheResult cacheResult = sindice.cacheQuery(cacheQuery);
//		String[] triples = cacheResult.getExplicitContent();
		
		String triples = liveQuery.performQuery(subjectUri).toString();
//		System.out.println(triples);
//		triples.replaceAll("[^\\u0000-\\uFFFF]", "");

		byte[] bytes;
		try {
			bytes = triples.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			triples.replaceAll("[^(\\x20-\\x7F)]", "?");
			bytes = triples.getBytes();
		}
		
		System.out.println(triples);
		
//		ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
//		
//		CharsetDecoder utf8Decoder = Charset.forName("UTF-8").newDecoder();
//		utf8Decoder.onMalformedInput(CodingErrorAction.IGNORE);
//		utf8Decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
//		CharBuffer parsed = utf8Decoder.decode(byteBuffer);
//		InputStream is = new ByteArrayInputStream(parsed.toString().getBytes());
		
		InputStream is = new ByteArrayInputStream(bytes);
		model.read(is, null, "N-TRIPLE"); //parse N-Triples using JENA#
		
//		if(triples.length == 0) {
//			System.out.println("NO TRIPLES RETURNED!");
//			return;
//		}
		
		//append all triples to string buffer
//		int z = 0;
//		for(z=0;z<triples.length;z++) {
//			System.out.println(triples[z]);
//			try {
//				//replace \" with nothing (occurs in some malformed urls and causes parse exceptions)
//				byte[] bytes = triples[z].getBytes();
//				InputStream is = new ByteArrayInputStream(bytes);
//				model.read(is, null, "N-TRIPLE"); //parse N-Triples using JENA#
//			}
//			catch (Exception e) {
//				byte[] bytes = triples[z].replace("\\\"", "").getBytes();
//				InputStream is = new ByteArrayInputStream(bytes);
//				model.read(is, null, "N-TRIPLE"); //parse N-Triples using JENA#
//			}
//		}
	}
}
